import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { visitLogDto, addVisitLogPostDto } from './dto/create-post.dot';
import { VisitLog } from './entities/log.entity';

import { Request } from 'express';

@Injectable()
export class VisitLogService {
  // 使用InjectRepository装饰器并引入Repository这样就可以使用typeorm的操作了
  constructor(
    @InjectRepository(VisitLog)
    private readonly VisitLogRepository: Repository<VisitLog>,
  ) {}
  
  // 添加访问
  async addVisitLog(body: addVisitLogPostDto, request: Request): Promise<any> {
    const paramData = {
      visit_mode: body.visit_mode,
      visit_browser: body.visit_browser,
      visit_ip: request.ip,
      visit_num: 1
    }
    const newVisitLog = await this.VisitLogRepository.create(paramData);
    await this.VisitLogRepository.save(newVisitLog)
    return [];
  }

  // 获取访问日志列表
  async logList(body): Promise<visitLogDto> {
    let tagsSql = ``;
    if(body && body.id) {
      tagsSql = `WHERE id = "${ body.id }"`;
    }
    const tagsList = await this.VisitLogRepository.query(`SELECT * FROM visit_log ${ tagsSql }`);
    return tagsList;
  }
}
